﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.IO;

namespace slCommunicator
{
    public class ContactInformation
    {
        public string DisplayName { get; set; }
        public string PictureProfileUrl { get; set; }
        public string Password { get; set; }

        protected byte[] passwordMd5;

        public byte[] PasswordMd5Byte { get { return passwordMd5; } }

        public ContactInformation(string dn, string ppu, string mp)
        {
            DisplayName = dn;
            PictureProfileUrl = ppu;
            Password = mp;

            if (string.IsNullOrEmpty(mp))
                return;

            passwordMd5 = MD5.Create().ComputeHash(Encoding.ASCII.GetBytes(mp));
        }

        private const string envelope = "<@ENVELOPE-CONTACT@>";
        public void WriteToStream(StreamWriter w)
        {
            w.WriteLine(envelope);
            w.WriteLine(Convert.ToBase64String(Encoding.UTF8.GetBytes(DisplayName)));
            w.WriteLine(Convert.ToBase64String(Encoding.UTF8.GetBytes(PictureProfileUrl)));
            w.WriteLine(envelope);
            w.Flush();
        }
        public void WriteToStream(Stream target)
        {
            StreamWriter writer = new StreamWriter(target);
            WriteToStream(writer);
        }

        public static ContactInformation ReadFromStream(StreamReader r)
        {
            string[] lines = new string[4];
            for (int i = 0; i < lines.Length; i++)
                lines[i] = r.ReadLine();

            if (lines[0] == lines[3] && lines[0] == envelope)
                return new ContactInformation(Encoding.UTF8.GetString(Convert.FromBase64String(lines[1])), Encoding.UTF8.GetString(Convert.FromBase64String(lines[2])), "");
            else
                return null;
        }

        public static ContactInformation ReadFromStream(Stream source)
        {
            StreamReader reader = new StreamReader(source);
            return ReadFromStream(reader);
        }

        private static ContactInformation _cc = null;
        public static ContactInformation MyContactInfo
        {
            get
            {
                if (_cc == null)
                {
                    _cc = new ContactInformation(Properties.Settings.Default.myContact_displayName, Properties.Settings.Default.myContact_pictureUrl, Properties.Settings.Default.myContact_password);
                }
                return _cc;
            }
            set
            {
                _cc = value;
            }
        }

        public override string ToString()
        {
            return string.Format("[({0}) & ({1})]", DisplayName, PictureProfileUrl);
        }
    }
}
